import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/api/user.dart';
import 'package:flutter_enjoy_plus/utils/PromptAction.dart';
import 'package:flutter_enjoy_plus/utils/TokenManager.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  TextEditingController textController = TextEditingController();
  TextEditingController codeController = TextEditingController();

  bool flag = false;
  Timer? _timer;
  int _count = 6;

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel(); //离开页面取消倒计时
  }

  void beginCountDown() {
    //倒计时
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _count--;
      });
      if (_count == 0) {
        flag = false;
        _timer?.cancel();

        setState(() {
          _count = 6;
        });
      }
    });
  }

  Widget getTimeShow() {
    if (_count < 6) {
      return Text('$_count秒后重新获取');
    }
    //60秒点击验证码
    return Text('获取验证码');
  }

  void sendCode() async {
    //节流保留第一次 用标记判断
    //防抖保留最后一次  用定时器  加延迟
    if (flag) return;
    flag = true;
    if (textController.text.isEmpty) {
      PromptAction.Error('你输入一下手机号');
      return;
    }
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(textController.text)) {
      PromptAction.Error('手机号码格式不正确');
      return;
    }
    // PromptAction.Info('success');
    var code = await sendCodeAPI({'mobile': textController.text});
    PromptAction.Info('验证码已发送  请查收');
    print(code);

    beginCountDown();
  }

  Future<void> login() async {
    if (textController.text.isEmpty) {
      PromptAction.Info('请输入手机号');
      return;
    }
    if (codeController.text.isEmpty) {
      PromptAction.Info('请输入验证码');
      return;
    }
    // 手机号格式校验
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(textController.text)) {
      PromptAction.Info('请输入正确的手机号');
      return;
    }
    // 验证码格式校验
    if (!RegExp(r'^\d{6}$').hasMatch(codeController.text)) {
      PromptAction.Info('请输入正确的验证码');
      return;
    }

    var res = await loginAPI(
        {'mobile': textController.text, 'code': codeController.text});
    print(res);

    //关闭倒计时
    _timer?.cancel();

    // 提示
    PromptAction.Success('登录成功');

    // 存token
    tokenManager.setToken(res['token']);

    // 跳转
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            const SizedBox(height: 10),
            Row(
              children: [
                Text(
                  '加入享+, 让生活更轻松',
                  style: TextStyle(fontSize: 15),
                )
              ],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: textController,
                    decoration: InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    // //倒计时开始
                    // beginCountDown();
                    sendCode();
                  },
                  child: getTimeShow(),
                ),
              ],
            ),
            const SizedBox(height: 8),
            TextField(
              controller: codeController,
              decoration: InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      // print(textController.text);
                      // print(codeController.text);
                      login();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
